<?php

namespace Modules\Coupon\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

class UserCoupon extends Model
{
    protected $guarded = [];
    protected $table = 'coupon_user';

    static public $resourceName = '优惠券';

    public function base_coupon()
    {
        return $this->belongsTo('\Modules\Coupon\Entities\Coupon', 'coupon_id');
    }

    // 当前时间可用的
    public function scopeUsableNow($query)
    {
        return $query->valid()->where('usable_start_at', '>', date('Y-m-d H:i:s'));
    }

    // 未使用的
    public function scopeValid($query)
    {
        return $query->whereNull('used_at')->where('usable_end_at', '>', date('Y-m-d H:i:s'));
    }

    // 已使用的
    public function scopeUsed($query)
    {
        return $query->whereNotNull('used_at');
    }

    // 过期的
    public function scopeExpired($query)
    {
        return $query->where('usable_end_at', '<', date('Y-m-d H:i:s'));
    }

    static public function initWith($coupon, $pushType = 'manual')
    {
        $usableStartAt = $coupon->usable_start_at;
        $usableEndAt = $coupon->usable_end_at;

        // pushType为优惠券领取类型
        $pushTypeMap = [
            'code' => 1,
            'manual' => 2,
            'system' => 3
        ];

        if ($coupon->time_limit_type === 1) {
            $usableStartAt = now();
            $usableEndAt = date('Y-m-d H:i:s', strtotime('+' . $coupon->valid_time . ' hours'));
        }

        $item = new UserCoupon([
            'uuid' => uniqid(),
            'coupon_id' => $coupon->id,
            'usable_start_at' => $usableStartAt,
            'usable_end_at' => $usableEndAt,
            'sale_type' => @$pushTypeMap[$pushType]
        ]);

        return $item;
    }

    public function isUsable($order)
    {
        // \Log::error($this->usable_end_at);
        // 未到优惠券开始使用的时间
        if ((String)$this->usable_end_at < date('Y-m-d H:i:s')) {
            return false;
        }

        return $this->base_coupon->isUsable($order);
    }

    public function use($order)
    {
        $this->update([
            'order_id' => $order->id,
            'used_at' => date('Y-m-d H:i:s')
        ]);

        if ($this->base_coupon)
            $this->base_coupon->update([
                'used_total' => $this->base_coupon->used_total + 1
            ]);
    }

    public function release()
    {
        $this->update([
            'order_id' => NULL,
            'used_at' => NULL
        ]);

        if ($this->base_coupon)
            $this->base_coupon->update([
                'used_total' => $this->base_coupon->used_total - 1
            ]);
    }
}
